package com.cmcc.shared


import android.app.Application
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.shared.config.SharedConfig.DRIVER_BREAK
import com.cmcc.shared.config.SharedConfig.DRIVER_NEW_ORDER
import com.cmcc.shared.config.SharedConfig.PASS_ORDER_COMPLEIE
import com.cmcc.shared.config.SharedConfig.PASS_ORDER_DRIVER_COME
import com.cmcc.shared.config.SharedConfig.PASS_ORDER_RECEIVED
import com.cmcc.shared.config.SharedConfig.PASS_ORDER_REFUSE
import com.cmcc.shared.config.SharedConfig.REFUSAL_ORDER
import com.cmcc.shared.config.SharedConfig.STATUS_UNKNOW
import com.cmcc.shared.network.NetWorkListener
import com.cmcc.shared.utils.L
import com.cmcc.shared.viewModel.SharedViewModel
import com.google.firebase.messaging.RemoteMessage
import skin.support.SkinCompatManager
import skin.support.app.SkinAppCompatViewInflater
import skin.support.app.SkinCardViewInflater
import skin.support.constraint.app.SkinConstraintViewInflater
import skin.support.design.app.SkinMaterialViewInflater

/**
 * Sdk的对外接口
 */
object SdkManager {
    const val LANGUAGE_ENG = 0//英文
    const val LANGUAGE_ZH_CN = 1//简体
    const val LANGUAGE_ZH_TW = 2//繁体

    var mLastPushTime: Long = 0
    private const val TIME_INTERVAL = 5000L

    private var currentLanguage = LANGUAGE_ZH_TW

    private var appContext: Context? = null
    private var fireBaseToken: String = ""
    private var myLinkToken: String = ""

    var logicHandler: IAppLogicHandler? = null
    fun init(handler: IAppLogicHandler) {
        logicHandler = handler
    }

    var netWorkListener: NetWorkListener? = null
    fun initNetWorkListener(listener: NetWorkListener) {
        netWorkListener = listener
    }


    /**
     * 设置语言
     * @param language 取值为LANGUAGE_ENG（0，默认）、LANGUAGE_ZH_CN（1）或者LANGUAGE_ZH_TW（2）
     */
    fun setLanguage(language: Int) {
        Log.e("当前语言", "SDK设置了语言:" + language)
        currentLanguage = language
    }

    fun getLanguage(): Int {
        return currentLanguage
    }

    /**
     * 处理推送
     * @param remoteMessage 收到的推送数据
     * @return 是否已经处理（未处理App会继续处理，已处理App会忽略该信息）
     */
    fun onMessageReceived(context: Context, remoteMessage: RemoteMessage): Boolean {
        val data = remoteMessage?.data

        val messageType = data?.get("messageType")

        if (messageType.isNullOrBlank()) {
            return false
        }
        L.d("onMessageReceived", "messageType: $messageType");

        val status = data?.get("status")
//        if (status.isNullOrBlank()) {
//            return false
//        }
        L.d("onMessageReceived", "status: $status");

        var intent: Intent? = null

        when (messageType.toInt()) {
            1 -> {//司机
                status?.let {
                    if (status.toInt() == 0) {//有乘客下订单
                        val nowTime = System.currentTimeMillis()
                        if (nowTime - mLastPushTime > TIME_INTERVAL) {
                            mLastPushTime = nowTime
                            intent = Intent(DRIVER_NEW_ORDER)
                        }
                    } else {
                        intent = Intent(STATUS_UNKNOW)
                    }
                }
            }
            2 -> {//乘客收到推送
                status?.let {
                    intent = when (status.toInt()) {
                        1 ->//有司机抢单，刷新乘客界面
                            Intent(PASS_ORDER_RECEIVED)
                        2, 3, 4, 5 ->//司机已到达，刷新乘客界面
                            Intent(PASS_ORDER_DRIVER_COME)
                        6 ->//已完成，刷新乘客界面
                            Intent(PASS_ORDER_COMPLEIE)
                        7 ->//后台拒绝订单
                            Intent(PASS_ORDER_REFUSE)


                        else ->
                            Intent(STATUS_UNKNOW)
                    }
                }
            }
            3 -> {//司机拒单后，刷新司机界面
                status?.let {
                    intent =
                        if (status.toInt() == 7) Intent(REFUSAL_ORDER) else Intent(STATUS_UNKNOW)
                }
            }
            5 -> {//司机休息
                intent = Intent(DRIVER_BREAK)
            }
        }


        val orderId = data?.get("orderId")
//        if (orderId.isNullOrBlank()) {
//            return false
//        }
        L.d("onMessageReceived", "orderId: $orderId");


        if (null != intent) {
            orderId?.let { intent?.putExtra("orderId", orderId) }
            intent?.putExtra("status", status)
            context.sendBroadcast(intent);
        }

        return true
    }


    fun inint(context: Context) {
        appContext = context

    }


    fun setApplicationContext(context: Context) {
        appContext = context
        Log.e("SdkManager", "调用init()把上下文传过来")
        //初始化SDK
        SkinCompatManager.withoutActivity(context as Application?)
            .addInflater(SkinAppCompatViewInflater())           // 基础控件换肤初始化
            .addInflater(SkinMaterialViewInflater())            // material design 控件换肤初始化[可选]
            .addInflater(SkinConstraintViewInflater())          // ConstraintLayout 控件换肤初始化[可选]
            .addInflater(SkinCardViewInflater())                // CardView v7 控件换肤初始化[可选]
            .setSkinStatusBarColorEnable(false)                     // 关闭状态栏换肤，默认打开[可选]
            .setSkinWindowBackgroundEnable(false)                   // 关闭windowBackground换肤，默认打开[可选]
            .loadSkin()

    }

    fun getApplicationContext(): Context? {
        return appContext
    }

    fun setFireBaseId(token: String) {
        fireBaseToken = token
    }

    fun getFireBaseId(): String {
        return fireBaseToken
    }

    fun setMyLinkToken(token: String) {
        myLinkToken = token
        if (!token.isNullOrBlank()) {
//            ARouter.getInstance().build("/shared/login").navigation()
            (getApplicationContext() as? Application)?.let {
                val viewModel =ViewModelProvider.AndroidViewModelFactory
                    .getInstance(
                        it
                    )
                    .create(SharedViewModel::class.java).userLogin(myLinkToken)
            }
        }

    }

    fun getMyLinkToken(): String {
        return myLinkToken
    }


}